package com.forlove.app.qselect.friend.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.friend.adapter.SearchFriendResultAdapter;
import com.forlove.app.qselect.friend.entity.FriendEntity;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.SearchFriendPresenter;
import com.forlove.app.qselect.friend.view.SearchFriendView;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 搜索好友页面
 * Created by yjl on 2017/10/14.
 */

public class SearchFriendActivity extends BaseActivity implements View.OnClickListener, TextWatcher, SearchFriendView {

    @BindView(R.id.edittext_input_query)
    AppCompatEditText edittext_input_query; //搜索输入框

    @BindView(R.id.text_cancel_query)
    AppCompatTextView cancelQuery;  //取消搜索

    @BindView(R.id.search_result_list)
    RecyclerView search_result_list;

    @BindView(R.id.view_search_friend)
    RelativeLayout view_search_friend;  //搜索输入的账号

    @BindView(R.id.text_query_str)
    AppCompatTextView text_query_str;  //显示查询的字段

    @BindView(R.id.view_friends)
    LinearLayout view_friends;
    private String queryStr = "";
    private SearchFriendResultAdapter searchFriendResultAdapter;

    private ArrayList<FriendEntity> friendEntities = new ArrayList<>();
    private ArrayList<FriendEntity> localFriend = new ArrayList<>();
    private SearchFriendPresenter searchFriendPresenter;
    private AnimatorSet animatorSetIn;
    private AnimatorSet animatorSetOut;
    private Animation animationIn;
    private Animation animationOut;
    private UserEntity userEntity;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_firends;
    }

    @Override
    public void initView() {
        searchFriendPresenter = new SearchFriendPresenter(this);
        userEntity = UserManager.getUesrInfo(this);
        cancelQuery.setOnClickListener(this);
        searchFriendResultAdapter = new SearchFriendResultAdapter(this,
                R.layout.item_search_friend, friendEntities, searchFriendPresenter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        search_result_list.setLayoutManager(linearLayoutManager);
        search_result_list.setAdapter(searchFriendResultAdapter);
        searchFriendResultAdapter.hideFooterView();
        showFriendListView();
        view_search_friend.setOnClickListener(this);
        edittext_input_query.addTextChangedListener(this);
        List<FriendEntity> entities = FriendManager.getFriends(this);
        if (entities.size() > 0) {
            localFriend.clear();
            localFriend.addAll(entities);
        }

    }

    private void showFriendListView() {
        if (friendEntities == null || friendEntities.size() == 0) {
            search_result_list.setVisibility(View.GONE);
        } else {
            search_result_list.setVisibility(View.VISIBLE);
        }
    }

    private List<FriendEntity> getLocalSearchFriend(String queryStr) {
        List<FriendEntity> local = new ArrayList<>();
        //手机号或者id
        for (FriendEntity friendEntity : localFriend) {
//            if (friendEntity.getAvaliableName().contains(queryStr)
//                    || friendEntity.mobile.contains(queryStr)) {
//                local.add(friendEntity);
//            }
            if (friendEntity.getSearchStatus(queryStr)) {
                local.add(friendEntity);
            }
        }
        return local;
    }

    private void updateResultView(List<FriendEntity> entities) {
        searchFriendResultAdapter.updateDatas(entities);
        if (entities != null && entities.size() > 0) {
            search_result_list.setVisibility(View.VISIBLE);
//            searchFriendResultAdapter.notifyDataSetChanged();
        } else {
            search_result_list.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_search_friend:
                requestSearchFriend();
                break;
            case R.id.text_cancel_query:
                onBackPressed();
                break;
        }
    }

    private void requestSearchFriend() {
        if (TextUtils.isEmpty(queryStr)) {
            return;
        }
        Map param = new HashMap();
        param.put("mobile", queryStr);
        searchFriendPresenter.loadSearchFriend(param);
    }

    private void showListView() {
        if (!view_friends.isShown()) {
            if (animationIn == null) {
                animationIn = AnimationUtils.loadAnimation(this, R.anim.toast_top_in);
                animationIn.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        view_friends.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            view_friends.setAnimation(animationIn);
            animationIn.start();
        }
    }

    private void hideListView() {
        if (view_friends.isShown()) {
            if (animationOut == null) {
                animationOut = AnimationUtils.loadAnimation(this, R.anim.dialog_fly_top_out);
                animationOut.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        view_friends.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            animationOut.setDuration(100);
            view_friends.setAnimation(animationOut);
            animationOut.start();
        }
    }

    private void showSearchParamView() {
        if (!view_search_friend.isShown()) {
            if (animatorSetIn == null) {
                animatorSetIn = new AnimatorSet();
                int height = view_search_friend.getHeight();
                final Animator animatorIn = ObjectAnimator.ofFloat(view_search_friend, "translationY",
                        -height, 0f);

                Animator view_friendsIn = ObjectAnimator.ofFloat(view_friends, "translationY",
                        0f, height);
                animatorSetIn.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        showListView();
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view_search_friend.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                animatorSetIn.setDuration(250);
                animatorSetIn.setInterpolator(new CycleInterpolator(2));
                animatorSetIn.playTogether(animatorIn, view_friendsIn);
            }
            animatorSetIn.start();
        }

    }


    private void hideParamView() {
        if (view_search_friend.isShown()) {
            if (animatorSetOut == null) {
                animatorSetOut = new AnimatorSet();
                int height = view_search_friend.getHeight();
                Animator animatorOut = ObjectAnimator.ofFloat(view_search_friend, "translationY",
                        0f, -height);
                Animator view_friendsOut = ObjectAnimator.ofFloat(view_friends, "translationY",
                        height, 0f);
                animatorSetOut.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        hideListView();
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view_search_friend.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                animatorSetOut.setDuration(100);
                animatorSetOut.setInterpolator(new CycleInterpolator(2));
                animatorSetOut.playTogether(animatorOut, view_friendsOut);

            }
            animatorSetOut.start();
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        text_query_str.setText(text);
        queryStr = text.toString().trim().replaceAll(" ", "");
        if (searchFriendResultAdapter != null) {
            searchFriendResultAdapter.setQueryString(queryStr);
        }
        if (!TextUtils.isEmpty(queryStr)) {
            showSearchParamView();
            List<FriendEntity> entities = getLocalSearchFriend(queryStr);
            updateResultView(entities);
        } else {
            updateResultView(new ArrayList<FriendEntity>());
            hideParamView();


        }
    }


    @Override
    public void afterTextChanged(Editable text) {
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String Msg) {
        Toast.makeText(this, Msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void showSearchViewData(SearchFriendEntity searchFriendEntity) {
        if (!StringUtils.isMobile(searchFriendEntity.friendEntity.mobile)) {
            Toast.makeText(this, "查无此人！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (searchFriendEntity != null && !searchFriendEntity.isFriend) {
            searchFriendEntity.friendEntity.charm = searchFriendEntity.note_times;
            if (userEntity != null && userEntity.userMobile.equals(searchFriendEntity.friendEntity.mobile)) {
                startActivity(new Intent(this, MineInfoActivity.class));
            } else {
                Intent intent = new Intent(this, SearchUserInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("friendinfo", searchFriendEntity);
                bundle.putString("mobile", searchFriendEntity.friendEntity.getAvaliableMobile());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        } else {
            //TODO 跳转好友详情页
            Toast.makeText(this, "此人已经是好友了", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, MineInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("mobile", searchFriendEntity.friendEntity.mobile);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }
}
